package susebs.pb.travel_server.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import susebs.pb.travel_server.domain.PageDto;
import susebs.pb.travel_server.domain.UserComment;
import susebs.pb.travel_server.entity.*;
import susebs.pb.travel_server.dao.CommentsDao;
import susebs.pb.travel_server.service.*;
import org.springframework.stereotype.Service;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import susebs.pb.travel_server.utils.TimeFormatUtil;

import javax.annotation.Resource;
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 评论表(Comments)表服务实现类
 *
 * @author makejava
 * @since 2024-02-05 08:02:26
 */
@Service("commentsService")
public class CommentsServiceImpl implements CommentsService {
    @Resource
    private CommentsDao commentsDao;
    @Resource
    private UsersService usersService;
    @Resource
    private PicturesService picturesService;
    @Resource
    private LandmarksService landmarksService;
    @Resource
    private PackagesService packagesService;
    @Resource
    private HotelsService hotelsService;

    /**
     * 通过ID查询单条数据
     *
     * @param commentId 主键
     * @return 实例对象
     */
    @Override
    public Comments queryById(Long commentId) {
        return this.commentsDao.queryById(commentId);
    }

    /**
     * 分页查询
     *
     * @param comments    筛选条件
     * @param pageRequest 分页对象
     * @return 查询结果
     */
    @Override
    public Page<Comments> queryByPage(Comments comments, PageRequest pageRequest) {
        long total = this.commentsDao.count(comments);
        return new PageImpl<>(this.commentsDao.queryAllByLimit(comments, pageRequest), pageRequest, total);
    }

    /**
     * 分页查询
     * 数据处理：评论和评分为空的过滤掉
     */
    @Override
    public PageInfo queryAllCommentsByPage(PageDto pageDto) {
        ArrayList<UserComment> res = new ArrayList<>();
        UserComment userComment;
        //空值处理
        if(pageDto.getPage() == null || pageDto.getSize() == null){
            pageDto.setPage(1);
            pageDto.setSize(10);
        }
        //asc原因：可能最新的评论预插入之后还未评论，如果倒序查得数据之后分页的话，会把有数据的评论分掉
        //解决方法：正序排序，随后在前端渲染时倒着来
        PageHelper.startPage(pageDto.getPage(), pageDto.getSize(),"comment_time asc");
        List<Comments> list = commentsDao.queryAllComments(pageDto.getComments());
        //过滤空值评论
        List<Comments> comments = list.stream().
                filter(comment -> comment.getComment() != null && comment.getCommentRating() != null)
                .collect(Collectors.toList());
        //查询评论对应用户信息和商家信息
        for (Comments c : comments) {
            userComment = new UserComment();
            //用户信息
            Users user = usersService.queryById(c.getUserId());
            Pictures picture = picturesService.queryPicturesByOwner(4, c.getUserId()).get(0);
            //商家信息
            Integer type = c.getRelatedEntityType();
            //景点
            if(type == 1){
                try {
                    Landmarks lm = landmarksService.queryById(c.getRelatedEntityId());
                    userComment.setShopName(lm.getLmName());
                }catch (Exception e){
                    userComment.setShopName("景区数据可能已被删除,评论作废");
                }

            }
            //套餐
            else if(type == 2){
                try {
                    Packages pk = packagesService.queryById(c.getRelatedEntityId());
                    userComment.setShopName(pk.getPkName());
                }catch(Exception e){
                    userComment.setShopName("套餐数据可能已被删除,评论作废");
                }
            }
            //酒店
            else if(type == 3){
                try {
                    Hotels hotel = hotelsService.queryById(c.getRelatedEntityId());
                    userComment.setShopName(hotel.getHotelName());
                }catch(Exception e){
                    userComment.setShopName("酒店数据可能已被删除,评论作废");
                }
            }

            //其他数据封装
            userComment.setComments(c);
            userComment.setUsers(user);
            userComment.setPictures(picture);
            userComment.setFormattedTime(TimeFormatUtil.timeFormat(c.getCommentTime()));

            res.add(userComment);
        }
        PageInfo<UserComment> pageInfo = new PageInfo<>(res);
        return pageInfo;
    }

    /**
     * 预插入数据
     * 作用：用户评论权限控制
     * 订单完成时数据预插入
     */
    @Override
    public Comments preInsert(Comments comments) {
        this.commentsDao.preInsert(comments);
        return comments;
    }

    /**
     * 用户评论
     * 1.根据userId+type+id反查comment_id--权限控制
     *      --如果有多个，则找 comment和comment_rating均为空的第一个
     *      --如果没有，则返回空comments，控制层如果接受到空对象，则表示该用户无评论权限
     * 2.根据comment_id进行数据填充--发布评论
     */
    @Override
    public Comments updateComments(Comments comment) {
        Long id = null;
        //请求参数设置--因为comment是带有待填充数据的，所以一定查不出数据
        Comments param = new Comments();
        param.setUserId(comment.getUserId());
        param.setRelatedEntityType(comment.getRelatedEntityType());
        param.setRelatedEntityId(comment.getRelatedEntityId());
        List<Comments> allComments = commentsDao.queryAllComments(param);
//        System.out.println("xxxxxxxxxxxxxxxxxxxx"+allComments);

        //用户无评论权限
        if(allComments.isEmpty()){
            return new Comments();
        }
        //用户有评论权限
        //选取第一个评论和评分均为空的数据--id正序查出，但是取值确实从最后一个开始取的
        for (Comments c:allComments) {
            if(c.getComment() == null&& c.getCommentRating() == null){
                id = c.getCommentId();
            }
        }
        //评论次数已满
        if(id == null){
            return new Comments();
        }
        comment.setCommentId(id);
        commentsDao.update(comment);

        return this.queryById(id);
    }


    /**
     * 用户删评
     * 业务逻辑：根据id将comment和comment_rating设置为空进修修改
     */
    @Override
    public boolean deleteComment(Long commentId) {
        int res = commentsDao.deleteComment(commentId);
        if(res == 0){
            System.out.println("修改失败！");
            return false;
        }else if(res == 1){
            return true;
        }else{
            System.out.println("错误！错误！未知错误！请立即检查数据库是否将comment_id设置为主键！");
            return false;
        }
    }

    /**
     * 修改数据
     *
     * @param comments 实例对象
     * @return 实例对象
     */
    @Override
    public Comments update(Comments comments) {
        this.commentsDao.update(comments);
        return this.queryById(comments.getCommentId());
    }

    /**
     * 通过主键删除数据
     *
     * @param commentId 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Long commentId) {
        return this.commentsDao.deleteById(commentId) > 0;
    }
}
